# 定义 ORM 模型
from tortoise.models import Model
from tortoise import fields


class User(Model):
    id = fields.IntField(pk=True)
    name = fields.CharField(max_length=50)
    age = fields.IntField()
    created_at = fields.DatetimeField(auto_now_add=True)

    class Meta:
        table = "users"     # 指定数据库表名


# 一对多关系(User -> Post): ForeignKeyField 定义外键关系，related_name 反向访问！
class Post(Model):
    id = fields.IntField(pk=True)
    title = fields.CharField(max_length=100)
    user = fields.ForeignKeyField("models.User", related_name="posts")  # 外键


# 多对多关系（User ↔ Course）:     # 多对多关系通过 ManyToManyField 轻松实现！
class Course(Model):
    id = fields.IntField(pk=True)
    name = fields.CharField(max_length=100)
    users = fields.ManyToManyField("models.User", related_name="courses")
